#include <stdio.h>
#include <string.h>
#include <iostream>
using std::cout;
using std::endl;

class String{
public:
    String()
    {
        cout<<"String()"<<endl;
    }

    String (const char *pstr )
        :_pstr(new char[strlen(pstr)+1]())
    {
        strcpy(_pstr,pstr);
        cout<<"String(const char*)"<<endl;
    }

    String (const String &rhs);
    String &operator=(const String &rhs);
    bool empty()const;
    int size()const;
    const char * c_str()const;
    ~String();
    String & append(String &rhs);
    String & append (const char *pstr);

private:
    char *_pstr;
};

String::String(const String &rhs){
    _pstr = new char[strlen(rhs._pstr)+1]();
    strcpy(_pstr,rhs._pstr);
    cout<<"String(const String &)"<<endl;
}

String & String::operator=(const String &rhs){
    if(&rhs != this){
        delete []_pstr;
        _pstr = new char[strlen(rhs._pstr)+1]();
        strcpy(_pstr,rhs._pstr);
    }
    cout<<"operator=(const String &)"<<endl;
    return *this;
} 

bool String::empty()const{
    if(_pstr){
        return true;
    }
    return false;
}

int String::size()const{
    return strlen(this->_pstr);
}

String::~String(){
    if(_pstr){
        delete[]_pstr;
        _pstr = nullptr;
    }
}

const char* String::c_str()const{
    return _pstr?_pstr:"";//null为测试输出
}

String & String::append(String &rhs){
    if(rhs._pstr){
    char *str = new char[strlen(_pstr)+strlen(rhs._pstr)+1]();
    strcpy(str,_pstr);
    delete[]_pstr;
    strcat(str,rhs._pstr);
    _pstr = str;
    }
    return *this ;
}

String & String::append(const char *pstr){
    if(pstr){
    char *str = new char[strlen(_pstr)+strlen(pstr)+1]();
    strcpy(str,_pstr);
    delete[]_pstr;
    strcat(str,pstr);
    _pstr = str;
    }
    return *this;
}


void test(){
    String s1;
    cout<<s1.empty()<<endl;
    String s2 ("hello");
    String s3 = s2;
    s1 = s2;
    cout<<s1.empty()<<endl;
    cout<<s2.size()<<endl;
    
    String s4("world");
    s4.append(s2);
    cout<<s4.size()<<endl;
    s4.append("c++");
    cout<<s4.size()<<endl;
    printf("%s\n",s4.c_str());//woldhelloc++
    cout<<s4.c_str()<<endl;
}

int main()
{


    test ();
    return 0;
}

